package cn.org.timespace.easyframe.util.generator;

import java.util.Date;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.org.timespace.easyframe.util.EfResourceContext;
import cn.org.timespace.easyframe.util.datatime.DateTimeUtils;

/**
 * <p>
 * 主键生成器
 * </p>
 * 
 * @version 1.0, 11/02/10
 * @since 1.0
 * @author 
 */

public class IdentityGenerator {
	
	private static final Log log = LogFactory.getLog(IdentityGenerator.class);
	
	private static IdentityGenerator identityGenerator;
	
	private static final String DEFAULT_PK_VALUE = "9999999999999999999999";
	private static final String DEFAULT_K_VALUE = "99999";
	private static final String PK_FILL_CHARACTER = "0";
	private static final String ORG_CODE = "org.code";
	private static String orgCode = "00";
	
	private static Integer increaseValue = 1;
	
	private IdentityGenerator(){}
	
	public static IdentityGenerator getInstance(){
		
		if(identityGenerator == null){
			if(log.isDebugEnabled()) log.debug("正在初始化主键生成器。");
			identityGenerator = new IdentityGenerator();
		}
		
		if(orgCode.equals("00")){
			orgCode = EfResourceContext.getInstance().getParamValue(ORG_CODE);
			if(log.isInfoEnabled()) log.info("机构编码是："+orgCode);
		}
		
		return identityGenerator;
	}
	
	public synchronized String getId(){
		String res = DEFAULT_PK_VALUE;
		
		String curDateTime = DateTimeUtils.formatDate(new Date(), DateTimeUtils.PATTERN_DATETIME_COMPACT);
		
		if(increaseValue >= Integer.MAX_VALUE){
			increaseValue = 1;
		}
		
		String fullC = fillCharacter(String.valueOf(increaseValue), PK_FILL_CHARACTER, 10);
		res = orgCode + curDateTime + fullC;
		increaseValue++;
		
		if(log.isInfoEnabled()) log.info("当前生成的主键是："+res);
		
		return res;
	}
	//获取应用平台ID，格式： a 20120326090517 00001
	public synchronized String getappId(){
		String res = DEFAULT_K_VALUE;
		if(increaseValue >= Integer.MAX_VALUE){
			increaseValue = 1;
		}
		String curDateTime = DateTimeUtils.formatDate(new Date(), DateTimeUtils.PATTERN_DATETIME_COMPACT);
		
		String fullC = fillCharacter(String.valueOf(increaseValue), PK_FILL_CHARACTER, 5);
		res =  "A"+curDateTime + fullC;
		increaseValue++;
		
		if(log.isInfoEnabled()) log.info("当前生成的主键是："+res);
		
		return res;
	}
	//获取信息终端ID，格式： m 20120326090517 00001
	public synchronized String getmacId(){
		String res = DEFAULT_K_VALUE;
		if(increaseValue >= Integer.MAX_VALUE){
			increaseValue = 1;
		}
		String curDateTime = DateTimeUtils.formatDate(new Date(), DateTimeUtils.PATTERN_DATETIME_COMPACT);
		
//		String fullC = fillCharacter(String.valueOf(increaseValue), PK_FILL_CHARACTER, 5);
		String fullC = getCharacterAndNumber(5);;
		
		res =  "M"+curDateTime + fullC;
		increaseValue++;
		
		if(log.isInfoEnabled()) log.info("当前生成的主键是："+res);
		
		return res;
	}
	
	//获取交换平台ID，格式： s 20120326090517 00001
	public synchronized String getmonId(){
		String res = DEFAULT_K_VALUE;
		if(increaseValue >= Integer.MAX_VALUE){
			increaseValue = 1;
		}
		String curDateTime = DateTimeUtils.formatDate(new Date(), DateTimeUtils.PATTERN_DATETIME_COMPACT);
		
		String fullC = fillCharacter(String.valueOf(increaseValue), PK_FILL_CHARACTER, 5);
		res =  "S"+curDateTime + fullC;
		increaseValue++;
		
		if(log.isInfoEnabled()) log.info("当前生成的主键是："+res);
		
		return res;
	}
	
	
	/**
	 * 填充字符
	 * @param oriC  原始字符
	 * @param fullC 填充字符
	 * @param size  总长度
	 * @return
	 */
	private String fillCharacter(String oriC,String fillC,int size){
		String res = "";
		if(oriC != null){
			int oriCLen = oriC.length();
			for(int i = size - oriCLen;i>0;i--){
				res += fillC;
			}
		}
		res += oriC;
		return res;
	}
	
	//生成字母和数字组成的随机码
	public synchronized String getCharacterAndNumber(int length)     
	{     
	    String val = "";     
	             
	    Random random = new Random();     
	    for(int i = 0; i < length; i++)     
	    {     
	        String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字     
	                 
	        if("char".equalsIgnoreCase(charOrNum)) // 字符串     
	        {     
//	            int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母     
	        	int choice = 65; //取得大写字母
	            val += (char) (choice + random.nextInt(26));     
	        }     
	        else if("num".equalsIgnoreCase(charOrNum)) // 数字     
	        {     
	            val += String.valueOf(random.nextInt(10));     
	        }     
	    }     
	             
	    return val;     
	} 


	
	public static void main(String[] args) {
		//for(int i=0;i<100;i++){
//			IdentityGenerator.getInstance().getappId();
		    for(int i=0;i<10;i++){
		    	System.out.println(IdentityGenerator.getInstance().getmacId());
		    }
			
		//}
	}
	
}
